

package cn.mabach.exception;

import cn.mabach.DTO.RS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常处理器
 *
 * @author Mark sunlightcs@gmail.com
 */
@ControllerAdvice
public class RExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(RException.class)
	public RS exceptionHandler(HttpServletRequest request, RException e){
		logger.info("URL : {}, error : {}", request.getRequestURL(),e.getMessage(), e);
		return RS.error(e.getCode(),e.getMessage());
	}

//	@ExceptionHandler(RException.class)
//	public RS handleRRException(RException e){
//		logger.error(e.getMessage(), e);
//		return RS.error(e.getCode(),e.getMessage());
//	}

	@ExceptionHandler(NoHandlerFoundException.class)
	public RS handlerNoFoundException(Exception e,HttpServletRequest request) {

		logger.error("URL : {}, error : {}", request.getRequestURL(), e.getMessage(),e);
		return RS.error(404, "路径不存在，请检查路径是否正确");
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public RS handleDuplicateKeyException(DuplicateKeyException e,HttpServletRequest request){
//		logger.error(e.getMessage(), e);
		logger.error("URL : {}, error : {}", request.getRequestURL(), e.getMessage(),e);
		return RS.error("数据库中已存在该记录");
	}

	@ExceptionHandler(DataIntegrityViolationException.class)
	public RS handleDataIntegrityViolationException(DataIntegrityViolationException e,HttpServletRequest request) {
//		logger.error(e.getMessage(), e);
		logger.error("URL : {}, error : {}", request.getRequestURL(), e.getMessage(),e);
		return RS.error("字段太长,超出数据库字段的长度");
	}




	@ExceptionHandler(MaxUploadSizeExceededException.class)
	public RS handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e,HttpServletRequest request) {
		logger.error(e.getMessage(), e);
		return RS.error("文件大小超出10MB限制, 请压缩或降低文件质量! ");
	}





	@ExceptionHandler(Exception.class)
	public RS handleException(Exception e){
		logger.error(e.getMessage(), e);
		return RS.error("操作失败");
	}
}
